<!-- 本页面用于： 物业品质-能源明细表(route不需要projectCode,projectName) | 商业,物业监控大屏-实时用电的详情页(route需要projectCode,projectName) | 专项报表中的能源消耗统计表(物业和商业)的详情页(route需要projectCode,projectName)
 route中的source： source!=dashboard表示 只有物业品质下的能源明细表查BI的数据,左上角可选项目; source=dashboard表示 其他都查自己业务的数据，左上角置灰
-->
<template>
	<div class="zs-table-page-container">
		<div class="zs-card-sm zs-space-bottom zs-layout-flex-row zs-layout-justify-between">
			<div>
				<el-input v-if="route.query.source == 'dashboard'" v-model="projectName" class="zs-select-md zs-space-right-sm" :disabled="true" placeholder="项目" />
				<el-select v-else class="zs-select-md zs-space-right-sm" v-model="searchObj.projectCode" :placeholder="'项目'" @change="queryList">
					<el-option v-for="item in projectList" :key="item.projectCode" :label="item.name" :value="item.projectCode" />
				</el-select>
				<el-input v-if="activeTab == 'area'" v-model="searchObj.deviceCode" class="zs-select-md zs-space-right-sm" maxlength="50" placeholder="设备编号" clearable />
				<el-input v-show="activeTab == 'business'" v-model="searchObj.wuTongBrandName" clearable class="zs-select-md zs-space-right-sm" placeholder="品牌名称" />
				<el-date-picker class="zs-space-right-sm" v-model="searchObj.queryTime" placeholder="日期" :clearable="false" value-format="x" @change="queryList" />
				<el-popover popper-class="zs-popper" placement="bottom-end" trigger="click">
					<template #reference>
						<el-button class="zs-btn-square-solid" :class="{ 'zs-btn-square-solid-active': searchObj.deviceName || searchObj.deviceNum }">
							<el-icon>
								<MoreFilled />
							</el-icon>
						</el-button>
					</template>
					<template #default>
						<el-input v-if="activeTab == 'area'" v-model="searchObj.deviceName" class="zs-select-md zs-space-right-sm" maxlength="50" placeholder="设备名称" clearable />
						<!-- <el-cascader v-if="activeTab == 'area'" class="zs-select-md zs-space-right-sm" @change="cascaderChange" v-model="searchObj.inventoryClass" :options="cascaderData" :props="cascaderProps" clearable placeholder="清单分类" filterable /> -->
						<el-input v-model="searchObj.deviceNum" class="zs-select-md zs-space-right-sm" maxlength="50" placeholder="电表号" clearable />
					</template>
				</el-popover>
				<el-button class="zs-btn-plain" @click="queryList"> 查询 </el-button>
			</div>
			<div class="zs-layout-flex-row zs-layout-items-center">
				<el-button :class="activeTab == 'area' ? 'zs-btn-primary' : 'zs-btn-info'" @click="tabChange('area')">公区</el-button>
				<el-button :disabled="route.query.source == 'dashboard' ? true : false" :class="activeTab == 'business' ? 'zs-btn-primary' : 'zs-btn-info'" @click="tabChange('business')">商户</el-button>
			</div>
		</div>

		<!-- teble -->
		<div class="zs-card zs-table-page-content">
			<el-table class="zs-table-page-main" :class="route.query.source == 'dashboard' ? 'zs-table-first-row-special' : ''" :data="tableData.data" v-loading="tableData.loading" stripe>
				<el-table-column v-if="route.query.source == 'dashboard'" label="序号" width="60" align="center" fixed>
					<template #default="scope">
						<span v-if="scope.$index == 0">合计</span>
						<span v-else>{{ scope.$index + (tableData.currentPage - 1) * curPageSize }}</span>
					</template>
				</el-table-column>
				<el-table-column v-else fixed type="index" label="序号" width="60" :align="'center'" :index="(index) => index + 1 + (tableData.currentPage - 1) * curPageSize" />
				<el-table-column prop="deviceNum" fixed label="电表号" show-overflow-tooltip align="left" minWidth="120" :formatter="defaultTableData" />
				<!-- <el-table-column prop="standardName" label="电表级别" show-overflow-tooltip align="center" minWidth="120" :formatter="defaultTableData" /> -->
				<!-- <el-table-column prop="standardName" label="父级电表号" show-overflow-tooltip align="left" minWidth="120" :formatter="defaultTableData" /> -->
				<el-table-column v-if="activeTab == 'business'" fixed prop="assetsNum" label="资产编号" show-overflow-tooltip align="left" minWidth="120" :formatter="defaultTableData" />
				<el-table-column v-if="activeTab == 'business'" fixed prop="wuTongBrandName" label="品牌名称" show-overflow-tooltip align="left" minWidth="120" :formatter="defaultTableData" />
				<!-- <el-table-column v-if="activeTab == 'area'" prop="level3Name" label="清单分类" show-overflow-tooltip align="left" minWidth="120" :formatter="defaultTableData" /> -->
				<el-table-column v-if="activeTab == 'area'" fixed label="设备名称" show-overflow-tooltip align="left" minWidth="200" :formatter="defaultTableData">
					<template #default="{ row }">
						<template v-if="row.deviceList && row.deviceList.length > 0">
							<span v-for="(item, index) in row.deviceList" :key="item.deviceCode">{{ item.deviceName }}({{ item.deviceCode }}){{ index < row.deviceList.length - 1 ? '，' : '' }}</span>
						</template>
					</template>
				</el-table-column>
				<!-- <el-table-column prop="standardName" label="异常点" show-overflow-tooltip align="center" :formatter="defaultTableData" /> -->
				<el-table-column prop="totalNumBit" label="合计" align="right" fixed :formatter="defaultTableData" show-overflow-tooltip />
				<el-table-column v-for="(item, index) in timeList" :key="item" :label="item" align="right" show-overflow-tooltip :formatter="defaultTableData">
					<template #default="{ row }">
						{{ row.dataList[index].synopsis }}
					</template>
				</el-table-column>
			</el-table>
			<div class="zs-space-top-sm zs-table-page-pagination">
				<el-pagination v-model:currentPage="tableData.currentPage" v-model:page-size="curPageSize" :page-sizes="curPageSizes" :small="true" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="tableData.total" @size-change="pageChange('size', $event)" @current-change="pageChange('page', $event)" />
			</div>
		</div>
	</div>
</template>

<script setup>
	import { ref, reactive } from 'vue';
	import Energy from '@/api/Energy';
	import { useStore } from 'vuex';
	import { useRoute } from 'vue-router';

	let store = useStore();
	const route = useRoute();
	const curPageSizes = ref(store.state.uiPageSizes);
	const curPageSize = ref(store.state.uiPageSizeDefault);

	// 级联规则
	// const cascaderProps = reactive({
	// 	checkStrictly: true,
	// 	value: 'code',
	// 	label: 'dictLabel',
	// });
	// 级联数据
	// let cascaderData = ref([]);
	// 级联变更
	// const cascaderChange = val => {
	// 	let cur = ['level1', 'level2', 'level3'];
	// 	if (val) {
	// 		cur.forEach((el, index) => {
	// 			searchObj[el] = val[index] || '';
	// 		});
	// 	} else {
	// 		cur.forEach(ele => {
	// 			searchObj[ele] = '';
	// 		});
	// 	}
	// 	queryList();
	// };

	// 列表 filed
	let tableData = reactive({
		currentPage: 1,
		total: 0,
		loading: false,
		data: [],
	});

	//查询条件
	let searchObj = reactive({ pageNumber: 1, pageSize: curPageSize.value, queryTime: '', projectCode: route.query.projectCode || '' });

	//项目
	const projectName = route.query.projectName ? ref(decodeURI(route.query.projectName)) : '';

	//tab查询
	let activeTab = ref('area');
	const tabChange = type => {
		activeTab.value = type;
		let clearFiledList = ['deviceName', 'wuTongBrandName', 'deviceCode', 'inventoryClass', 'level1', 'level2', 'level3', 'deviceNum'];
		clearFiledList.forEach(filed => {
			searchObj[filed] = '';
		});
		searchObj.pageNumber = 1;
		initTime();
		queryList();
	};

	//列表数据源
	const queryList = async () => {
		tableData.loading = true;
		let res = {};
		if (route.query.source == 'dashboard') {
			res = await Energy.energyElectricitydashboardAreaListApi(searchObj);
		} else {
			res = activeTab.value == 'business' ? await Energy.energyElectricityBusinessListApi(searchObj) : await Energy.energyElectricityListApi(searchObj);
		}
		if (res.data.code !== 200) return;
		let sourceList = res.data.data.list;
		if (sourceList.length > 0) {
			if (route.query.source == 'dashboard') {
				sourceList.unshift({ totalNum: res.data.data.totalNum, dataList: res.data.data.totalList });
			}
			sourceList.forEach(item => {
				item.totalNumBit = !isNaN(item.totalNum) ? Number(item.totalNum).toFixed(1) : '-';
				item.dataList &&
					item.dataList.forEach(hourItem => {
						hourItem.synopsis = !isNaN(hourItem.dosage) ? Number(hourItem.dosage).toFixed(1) : '-';
					});
			});
			tableData.data = sourceList;
		}
		tableData.data = sourceList || [];
		tableData.total = res.data.data.total || 0;
		tableData.loading = false;
	};

	// 分页
	const pageChange = (type, size) => {
		if (type == 'size') {
			searchObj.pageSize = size;
		} else {
			searchObj.pageNumber = size;
		}
		queryList();
	};

	// 昨天00:00 的时间戳
	const getYesterdayMidnightTimestamp = () => {
		const now = new Date();
		now.setHours(0, 0, 0, 0); // 设置今天零时
		const yesterdayMidnight = new Date(now.getTime() - 24 * 60 * 60 * 1000); // 减去一天
		return yesterdayMidnight.getTime();
	};

	const initTime = () => {
		searchObj.queryTime = route.query.projectCode ? Number(route.query.showTimeStamp) : getYesterdayMidnightTimestamp();
	};

	// 清单分类
	// const queryAllClassificationData = async () => {
	// 	let res = await Energy.getAllClassificationDataApi();
	// 	cascaderData.value = res.data.data || [];
	// };

	// 项目
	const projectList = ref([]);
	const getProjectList = async () => {
		let res = await Energy.energyProjectListApi();
		projectList.value = res.data.data;
		searchObj.projectCode = projectList.value.length > 0 ? projectList.value[0].projectCode : '';
		queryList();
	};

	//获取24个小时list
	let timeList = ref([]);
	const generateTimeList = () => {
		const list = [];
		for (let i = 1; i <= 24; i++) {
			const hour = i < 10 ? `0${i}` : i;
			const time = `${hour}:00`;
			list.push(time);
		}
		timeList.value = list;
	};

	const defaultTableData = (row, column, cellValue, index) => {
		let emptyVal = index == 0 ? '' : '-';
		return cellValue || cellValue === 0 ? cellValue : emptyVal;
	};

	initTime();
	generateTimeList();
	// queryAllClassificationData();
	if (route.query.source == 'dashboard') {
		queryList();
	} else {
		getProjectList();
	}
</script>
